<template>
  <div>
    <a-card>
      <a-form-model ref="form" layout="inline" :model="form">
        <a-row type="flex">
          <a-col>
            <!-- <a-form-model-item label="破壁人" prop="user">
              <a-input v-model="form.user" placeholder="请输入破壁人" />
            </a-form-model-item> -->
            <a-form-model-item label="状态" prop="state">
              <a-select
                v-model="form.state"
                placeholder="请选择状态"
                style="width:120px"
                :options="[ { value: 'NEW', label: '新创建' }, { value: 'DONE', label: '已完成' }]"
              />
            </a-form-model-item>
            <a-form-model-item label="到期日" prop="dueDate">
              <a-range-picker
                v-model="form.dueDate"
              />
            </a-form-model-item>
            <a-form-model-item>
              <a-button type="primary" @click="handleSearch">
                查找
              </a-button>
            </a-form-model-item>
            <a-form-model-item>
              <a-button type="primary" @click="handleReset">
                重置
              </a-button>
            </a-form-model-item>
          </a-col>
          <a-col v-if="fetchType==='me'">
            <a-form-model-item style="float:right;">
              <a-button type="primary" @click="showEditMissionModal(undefined)">
                新增
              </a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <a-table
        :loading="loading"
        rowKey="id"
        :columns="missionColumns"
        :data-source="data"
        class="mission-list__table"
        :expandedRowKeys="expandedRowKeys"
        @expand="expand"
      >
        <template slot="status" slot-scope="record">
          <span v-if="record.state === 'NEW'"><a-badge status="processing" /> {{ record.stateDesc }}</span>
          <span v-if="record.state === 'DONE'"><a-badge status="success" /> {{ record.stateDesc }}</span>
        </template>
        <template slot="operation" slot-scope="record" >
          <div>
            <router-link :to="`/mission/detail/${record.id}`" style="margin-right: 10px">详情</router-link>
            <template v-if="fetchType==='me'">
              <a-dropdown :trigger="['click']" style="margin-right: 10px">
                <a size="small" @click="e=>e.preventDefault()">更多<a-icon type="small-dash" /></a>
                <a-menu slot="overlay">
                  <a-menu-item key="0">
                    <a @click="showEditMissionModal(record)">编辑</a>
                  </a-menu-item>
                  <a-menu-item key="1">
                    <a @click="del(record.id)">删除</a>
                  </a-menu-item>
                  <a-menu-divider />

                  <a-menu-item key="3" v-if="record.state==='NEW'">
                    <a @click="showAddInstanceModal(record)">加入我的团战</a>
                  </a-menu-item>
                  <a-menu-item key="4" v-if="record.state==='NEW'">
                    <a @click="showAddResultModal(record)">添加关键结果</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
            <template v-if="actorId !== record.actorId">
              <a @click="showInviteMissionModal(record)">邀请</a>
            </template>
          </div>
        </template>

        <a-table
          rowKey="keyResultId"
          slot="expandedRowRender"
          slot-scope="record"
          :loading="record.loading"
          :columns="resultsColumns"
          :data-source="record.innerData"
        >
          <template slot="status" slot-scope="resultRecord">
            <span v-if="resultRecord.keyResultState === 'NEW'"><a-badge status="processing" /> {{ resultRecord.keyResultStateDesc }}</span>
            <span v-if="resultRecord.keyResultState === 'DONE'"><a-badge status="success" /> {{ resultRecord.keyResultStateDesc }}</span>
          </template>
          <span slot="operation" slot-scope="resultRecord" class="table-operation">
            <a @click="deleteKeyResult(record, resultRecord.keyResultId)">删除</a>
          </span>
        </a-table>
      </a-table>
    </a-card>

    <edit-mission-modal
      ref="editMissionModal"
      @finished="updateList"
    />
    <add-result-modal
      ref="addResultModal"
      @finished="updateResultList"
    />
    <add-instance-modal
      ref="addInstanceModal"
      @finished="updateResultList"
    />
    <invite-mission-modal
      ref="inviteMissionModal"
      @finished="updateResultList"
    />
  </div>
</template>

<script>
// 组件
import EditMissionModal from './components/edit-mission'
import AddResultModal from './components/add-result'
import AddInstanceModal from './components/add-instance'
import InviteMissionModal from './components/invite-mission'

// api
import { fetchAllMissions, fetchMyMissions, detail, deleteKeyResult, del } from '@/api/mission'

// tools
import { mapGetters } from 'vuex'

// 常量
import { missionColumns, resultsColumns } from './constants'

export default {
  props: {
    fetchType: {
      type: String,
      required: true
    }
  },
  components: {
    EditMissionModal,
    AddResultModal,
    AddInstanceModal,
    InviteMissionModal
  },
  data () {
    return {
      loading: false,
      form: {
        user: undefined,
        region: undefined,
        dueDate: undefined
      },
      expandedRowKeys: [],
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0
      },
      missionColumns,
      data: [],
      resultsColumns
    }
  },
  mounted () {
    this.handleSearch(true)
  },
  computed: {
    ...mapGetters(['actorId'])
  },
  methods: {
    async handleSearch (valid) {
      try {
        this.loading = true
        if (!valid) { throw new Error() }
        let fetchMission = () => {}
        const params = {
          ...this.form,
          pageNumber: 1,
          pageSize: 1000
        }
        switch (this.fetchType) {
          case 'me':
            fetchMission = fetchMyMissions
            break
          case 'all':
            fetchMission = fetchAllMissions
            params.isInGroup = false
            break
        }
        const content = await fetchMission(params)
        content.forEach(record => {
          record.loading = false
          record.innerData = []
        })
        this.data = content
      } catch (error) {
        this.$notification.error({
          message: '错误',
          description: error.message || '请求信息错误，请稍后重试'
        })
      } finally {
        this.loading = false
      }
    },

    async updateList () {
      await this.handleSearch(true)
      const recordId = this.expandedRowKeys[0]
      const record = this.data.find(item => (item.id === recordId))
      if (record) {
        this.getInnerData(record)
      }
    },

    async del (id) {
      try {
        this.loading = true
        await del(id)
        this.updateList()
      } catch (error) {

      } finally {
        this.loading = false
      }
    },

    handleReset () {
      this.$refs.form.resetFields()
    },

    showEditMissionModal (id) {
      this.$refs.editMissionModal.show(id)
    },
    showAddResultModal (reocrd) {
      this.$refs.addResultModal.show(reocrd)
    },
    expand (expanded, record) {
      if (expanded) {
        this.expandedRowKeys.splice(0, 1, record.id)
        this.getInnerData(record)
      } else {
        this.expandedRowKeys.splice(0, 1)
      }
    },
    async getInnerData (record) {
      try {
        record.loading = true
        const missionId = record.id
        const content = await detail({ missionId })
        record.innerData = content.keyResultList
      } catch (error) {

      } finally {
        record.loading = false
      }
    },
    // 更新内部列表
    updateResultList (record) {
      if (record.id === this.expandedRowKeys[0]) {
        this.getInnerData(record)
      }
    },
    async deleteKeyResult (record, keyResultId) {
      console.log(record, keyResultId)
      try {
        record.loading = true
        await deleteKeyResult(keyResultId)
        this.updateResultList(record)
      } catch (error) {

      } finally {
        record.loading = false
      }
    },

    // 加入团战
    showAddInstanceModal (record) {
      this.$refs.addInstanceModal.show(record)
    },
    // 邀请目标
    showInviteMissionModal (record) {
      this.$refs.inviteMissionModal.show(record)
    }
  }
}
</script>
<style lang="less">
.mission-list{
  &__table {
    margin-top: 10px;
  }
}
</style>
